package com.smr.micservice.apigateway.filter;

import com.netflix.zuul.ZuulFilter;
import com.netflix.zuul.context.RequestContext;
import com.netflix.zuul.exception.ZuulException;
import com.smr.micservice.apigateway.utils.CusAccessObjectUtil;
import com.smr.micservice.common.AuthConst;
import com.smr.micservice.common.exception.ParamsValidException;
import com.smr.micservice.common.pojo.ErrorMessage;
import com.smr.micservice.common.utils.JsonUtil;
import io.jsonwebtoken.Jwts;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;

import javax.servlet.http.HttpServletRequest;

/**
 * token拦截器
 *
 * @author shi_mengran
 */
public class TokenFilter extends ZuulFilter {

    @Override
    public String filterType() {
        return "pre";
    }

    @Override
    public int filterOrder() {
        return 0;
    }

    @Override
    public boolean shouldFilter() {
        return true;
    }

    @Override
    public Object run() throws ZuulException {
        RequestContext currentContext = RequestContext.getCurrentContext();
        HttpServletRequest request = currentContext.getRequest();
        if (request.getRequestURI().endsWith("/v2/api-docs")) {
            currentContext.setSendZuulResponse(true);
            return null;
        }
        String header = request.getHeader("Authentication");
        addPassHeader(currentContext, request);
        try {
            String start = "QQXB_";
            if (header.startsWith(start)){
                header = header.replace(start, "");
                Jwts.parser()
                        .setSigningKey("WSRSDL_2018_SNCN0088")
                        .parseClaimsJws(header)
                        .getBody();
                currentContext.getResponse().setHeader(AuthConst.STATUS_HEADER, AuthConst.SUCCESS);
                currentContext.setSendZuulResponse(true);
            } else {
                throw new ParamsValidException("TOKEN错误");
            }
        } catch (Exception e) {
            currentContext.setSendZuulResponse(false);
            currentContext.setResponseStatusCode(HttpStatus.BAD_REQUEST.value());
            currentContext.getResponse().setContentType(MediaType.APPLICATION_JSON_UTF8_VALUE);
            currentContext.getResponse().setHeader(AuthConst.STATUS_HEADER, AuthConst.OVERTIME);
            ErrorMessage errorMessage = new ErrorMessage(HttpStatus.BAD_REQUEST.value(), "登陆过期，请重新登陆");
            String error = JsonUtil.toJson(errorMessage);
            currentContext.setResponseBody(error);
        }
        //这里的return,zuul框架并没有使用
        return null;
    }

    private void addPassHeader(RequestContext currentContext, HttpServletRequest request) {
        String ipAddress = CusAccessObjectUtil.getIpAddress(request);
        currentContext.addZuulRequestHeader("Ip-Address", ipAddress);
    }
}
